package com.lyw.login

import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.lu.library.base.BaseActivity
import com.lyw.container.ContainerActivity
import com.lyw.login.databinding.ActivityRegisterBinding
import com.lyw.login.vm.RegisterIntent
import com.lyw.login.vm.RegisterUiState
import com.lyw.login.vm.RegisterVm
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class RegisterActivity : BaseActivity<ActivityRegisterBinding>() {

    private val registerVm by viewModels<RegisterVm>()
    override fun initViews() {
        super.initViews()
    }
    override fun initListener() {
        super.initListener()
        binding.etPhone.addTextChangedListener {
            registerVm.sendUiIntent(RegisterIntent.PhoneChange(it.toString()))
        }
        binding.etPwd.addTextChangedListener {
            registerVm.sendUiIntent(RegisterIntent.PwdChange(it.toString()))
        }
        binding.etCode.addTextChangedListener {
            registerVm.sendUiIntent(RegisterIntent.CodeChange(it.toString()))
        }

        binding.tvSendCode.setOnClickListener {
            registerVm.sendUiIntent(RegisterIntent.SendCode(binding.etPhone.text.toString()))
        }
        binding.tvRegister.setOnClickListener {
            registerVm.sendUiIntent(RegisterIntent.Register(binding.etPhone.text.toString(),
                binding.etPwd.text.toString()))
        }
    }
    override fun initData() {

        lifecycleScope.launch {
            registerVm.uiStateFlow.collect{
                when(it){
                    is RegisterUiState.INIT ->{
                        binding.tvRegister.isEnabled = false
                        binding.tvSendCode.isEnabled = false
                    }
                    is RegisterUiState.CountDown -> {
                        binding.tvSendCode.text = it.countDown
                        binding.tvSendCode.isEnabled = it.codeEnable
                    }
                    RegisterUiState.LoginSuccess -> {
                        ToastUtils.showLong("注册成功")
                        startActivityAndSelfFinish(ContainerActivity::class.java)
                    }
                    is RegisterUiState.LoginEnable->{
                        binding.tvRegister.isEnabled = it.loginEnable
                    }
                    is RegisterUiState.SendCodeEnable -> {
                        binding.tvSendCode.isEnabled = it.codeEnable
                    }
                }
            }
        }

    }

    override fun layoutResId(): Int = R.layout.activity_register
}